package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.config.MinioConfig;
import com.atguigu.gmall.product.config.properties.MinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author:lyd
 * @Date:2023/8/15 23:58
 * @Version:1.0
 * @Description
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) throws Exception {
        //以日期作为文件夹
        String folder = DateUtil.formatDate(new Date(), "yyyy/MM/dd");
        String fileName = folder + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "-"+file.getOriginalFilename();
        String path=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;

        //1.把file存到minio服务器
        //1.1创建 MinioClient
        //1.2文件上传参数构造
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(fileName)//对象存储中用的名字
                .stream(file.getInputStream(), file.getSize(), -1L)
                .contentType(file.getContentType())
                .build();
        //1.3上传
        minioClient.putObject(putObjectArgs);
        return path;
    }
}
